home *** CD-ROM | disk | FTP | other *** search
/ Aminet 40 / Aminet 40 (2000)(Schatztruhe)[!][Dec 2000].iso / Aminet / dev / lang / Python16.lha / Python-1.6 / Lib / Python1.6 / test / test_fork1.py < prev    next >
Encoding:
Python Source  |  2000-05-04  |  1.4 KB  |  69 lines

  1. """This test checks for correct fork() behavior.
  2.  
  3. We want fork1() semantics -- only the forking thread survives in the
  4. child after a fork().
  5.  
  6. On some systems (e.g. Solaris without posix threads) we find that all
  7. active threads survive in the child after a fork(); this is an error.
  8.  
  9. """
  10.  
  11. import os, sys, time, thread
  12.  
  13. try:
  14.     os.fork
  15. except AttributeError:
  16.     raise ImportError, "os.fork not defined -- skipping test_fork1"
  17.  
  18. LONGSLEEP = 2
  19.  
  20. SHORTSLEEP = 0.5
  21.  
  22. NUM_THREADS = 4
  23.  
  24. alive = {}
  25.  
  26. stop = 0
  27.  
  28. def f(id):
  29.     while not stop:
  30.         alive[id] = os.getpid()
  31.         try:
  32.             time.sleep(SHORTSLEEP)
  33.         except IOError:
  34.             pass
  35.  
  36. def main():
  37.     for i in range(NUM_THREADS):
  38.         thread.start_new(f, (i,))
  39.  
  40.     time.sleep(LONGSLEEP)
  41.  
  42.     a = alive.keys()
  43.     a.sort()
  44.     assert a == range(NUM_THREADS)
  45.  
  46.     prefork_lives = alive.copy()
  47.  
  48.     cpid = os.fork()
  49.  
  50.     if cpid == 0:
  51.         # Child
  52.         time.sleep(LONGSLEEP)
  53.         n = 0
  54.         for key in alive.keys():
  55.             if alive[key] != prefork_lives[key]:
  56.                 n = n+1
  57.         os._exit(n)
  58.     else:
  59.         # Parent
  60.         spid, status = os.waitpid(cpid, 0)
  61.         assert spid == cpid
  62.         assert status == 0, "cause = %d, exit = %d" % (status&0xff, status>>8)
  63.         global stop
  64.         # Tell threads to die
  65.         stop = 1
  66.         time.sleep(2*SHORTSLEEP) # Wait for threads to die
  67.  
  68. main()
  69.